package it.polimi.swKnights.SWIMv2.servlets.administration;

import it.polimi.swKnights.SWIMv2.ejb.administration.BanUserRemote;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.IllegalBanException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class BanProcessData
 */
public class BanProcessData extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		HttpSession session = request.getSession();
		String admin = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");

		String userToBan = request.getParameter("userToBan");
		Integer banDays;
		try
		{
			banDays = Integer.parseInt(request.getParameter("banDays"));
			if(banDays < 0)
			{
				response.sendRedirect("./administration");
				return;
			}
		}
		catch(Exception e)
		{
			response.sendRedirect("./administration");
			return;
		}

		BanUserRemote banBean = this.lookUp(BanUserRemote.class);

		try
		{
			banBean.banUser(userToBan, banDays, admin, password);
			response.sendRedirect("./administration?banned=" + userToBan);
		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./administration?error=" + Errors.notadmin);
		}
		catch (EJBException e)
		{
			response.sendRedirect("./administration?error=" + Errors.notbanned);
		}
		catch (IllegalBanException e)
		{
			response.sendRedirect("./administration?error=" + Errors.banadmin);
		}

	}

}
